#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <sys/time.h>
#ifdef __aarch64__
#include "ifm_nettle/md5.h"
#define md5_ctx ifm_md5_ctx
#else
#include "nettle/md5.h"
#endif

#define SHOW_LOG false
#define MAX_BLOCK_SZ    1024*1024*1        // 每次hash分段的最大长度

// nettle包中的MD5接口使用
int imf_nettle_md5_damo(unsigned int times, uint8_t *data)
{
    struct md5_ctx ctx;
    char hex_digest[MD5_DIGEST_SIZE * 2 + 1];
    uint8_t digest[MD5_DIGEST_SIZE];
    const uint8_t *data_pt;

    size_t length = strlen(data);
    size_t total_len = 0;

    if (SHOW_LOG)
        printf("===========This is test for nettle MD5: %s\n", data);

    md5_init(&ctx);
    do
    {
        data_pt = data + total_len;
        // 分段输入，每段大小为MAX_BLOCK_SZ
        if (total_len + MAX_BLOCK_SZ <= length)
        {
            md5_update(&ctx, MAX_BLOCK_SZ, data_pt);
            total_len += MAX_BLOCK_SZ;
        }
        else
        {
            md5_update(&ctx, length-total_len, data_pt);
            total_len = length;
        }
    } while (total_len < length);
    
    md5_digest(&ctx, MD5_DIGEST_SIZE, digest);
    if (times <= 5)
    {
        for (int i = 0; i < MD5_DIGEST_SIZE; i++)
        {
            sprintf(hex_digest + i * 2, "%02x", digest[i]);
        }
        printf("MD5: %s\n", hex_digest);
    }

    return 0;
}
